package com.thread.threadpractice.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
public class TestController {

    @RequestMapping("/StringBuilder")
    public Integer stringBuilder() throws InterruptedException {
        List<String> list = new ArrayList<>(Collections.nCopies(1000, "1"));
        StringBuilder stringBuilder = new StringBuilder();
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                // 每个线程拼接1000次
                stringBuilder.append("1".repeat(1000));
            });
            thread.start();
            threads.add(thread);

        }
        for (Thread t : threads) {
            t.join();
        }

        return stringBuilder.length();
    }

    @RequestMapping("/StringBuffer")
    public Integer stringBuffer() throws InterruptedException {
        List<String> list = new ArrayList<>(Collections.nCopies(1000, "1"));
        StringBuffer stringBuffer = new StringBuffer();
        List<Thread> threads = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                // 每个线程拼接1000次
                stringBuffer.append("1".repeat(1000));
            });
            thread.start();
            threads.add(thread);

        }

        for (Thread t : threads) {
            t.join();
        }
        return stringBuffer.length();
    }
}
